﻿
using Microsoft.AspNetCore.Mvc;
using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Linq;
using MiniErp.Entity.DataStreams.BOs;

namespace MiniErp.Common.Cache
{
    /// <summary>
    /// Redis缓存
    /// </summary>
    public class RedisCache : ICache
    {
        /// <summary>
        /// 缓存Key类型是否符合规范
        /// </summary>
        /// <param name="type">Key类型 必须是CacheKeyType中成员变量</param>
        /// <returns></returns>
        private void KeyTypeValidation(string type)
        {
            var types = typeof(CacheKeyType).GetFields();
            foreach (var item in types)
            {
                if (item.GetValue(item) as string == type)
                {
                    return;
                }
            }
            throw new ExceptionBO($"缓存类型{type}不符合缓存类型约束", 500);
        }

        public Task<long> DelAsync(string type, params string[] key)
        {
            KeyTypeValidation(type);
            return RedisHelper.DelAsync($"{type}{key}");
        }

        public Task<bool> ExistsAsync(string type, string key)
        {
            KeyTypeValidation(type);
            return RedisHelper.ExistsAsync($"{type}{key}");
        }

        public Task<string> GetAsync(string type, string key)
        {
            KeyTypeValidation(type);
            return RedisHelper.GetAsync($"{type}{key}");
        }

        public async Task<T> GetAsync<T>(string type, string key)
        {
            KeyTypeValidation(type);
            return await RedisHelper.GetAsync<T>($"{type}{key}");
        }

        public Task<string[]> GetAsyncByWildCard(string wildcard)
        {
            return RedisHelper.KeysAsync(wildcard);
        }


        public Task<bool> SetAsync(string type, string key, object value)
        {
            KeyTypeValidation(type);
            return RedisHelper.SetAsync($"{type}{key}", value);
        }

        public Task<bool> SetAsync(string type, string key, object value, TimeSpan expire)
        {
            KeyTypeValidation(type);
            return RedisHelper.SetAsync($"{type}{key}", value, expire);
        }

        public Task<long> SAddAsync(string type, string key, object value)
        {
            KeyTypeValidation(type);
            return RedisHelper.SAddAsync($"{type}{key}", value);
        }

        public Task<long> SAddAsync(string type, string key, object value, TimeSpan expire)
        {
            KeyTypeValidation(type);
            return RedisHelper.SAddAsync($"{type}{key}", value, expire);
        }
    }
}
